package com.chcit.mobile.mvp.common.model;

import android.app.Application;

import com.chcit.mobile.mvp.common.api.cache.CommonCache;
import com.chcit.mobile.mvp.common.api.service.UserService;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.ActivityScope;

import javax.inject.Inject;

import com.chcit.mobile.mvp.common.contract.TaskContract;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


@ActivityScope
public class TaskModel extends BaseModel implements TaskContract.Model {
    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public TaskModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }

    public Observable<List<BpartnerBean>> getBparenerBeans() {
        //使用rxcache缓存,上拉刷新则不读取缓存,加载更多读取缓存
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("accessAll","N");
        return Observable.just(mRepositoryManager
                .obtainRetrofitService(UserService.class)
                .queryBpartners().map(jsonObject1 -> jsonObject1.getJSONArray("rows").toJavaList(BpartnerBean.class)
                ))
                .flatMap((Function<Observable<List<BpartnerBean>>, ObservableSource<List<BpartnerBean>>>) bpartnerBeans -> mRepositoryManager.obtainCacheService(CommonCache.class)
                        .getBpartners(bpartnerBeans)).subscribeOn(Schedulers.io());
    }
}